package migration

import (
	"errors"
	"fmt"
	"github.com/wuzfei/go-helper/rand"
	"go.uber.org/zap"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"onvif_server/internal/model"
	"onvif_server/internal/model/field"
)

type Config struct {
	Username string `help:"超级管理员名称" default:"admin"`
	Password string `help:"超级管理员密码" default:""`
}

type Migration struct {
	config *Config
	db     *gorm.DB
	log    *zap.Logger
}

func NewMigration(conf *Config, log *zap.Logger, db *gorm.DB) *Migration {
	return &Migration{
		config: conf,
		db:     db,
		log:    log,
	}
}

func (m *Migration) InitTables() error {
	return m.db.AutoMigrate(
		&model.User{},
		&model.Camera{},
		&model.Setting{},
		&model.Subscription{},
		&model.Alarm{},
	)
}

// InitAdminAccount 初始化超管账户
func (m *Migration) InitAdminAccount() error {
	mUser := model.User{
		ID:       model.SuperUserId,
		Username: "admin",
		Status:   field.StatusEnable,
	}
	//设置密码
	var pwd []byte
	if m.config.Password == "" {
		pwd = []byte(rand.StringN(12))
	} else {
		if len(m.config.Password) < 6 || len(m.config.Password) > 32 {
			return errors.New("密码至少设置6个字符,最长32个字符")
		}
		pwd = []byte(m.config.Password)
	}
	mUser.Password, _ = bcrypt.GenerateFromPassword(pwd, bcrypt.DefaultCost)

	//设置账号
	if m.config.Username != "" {
		mUser.Username = m.config.Username
	}
	err := m.db.Clauses(clause.OnConflict{
		UpdateAll: true,
	}).Create(&mUser).Error
	if err != nil {
		m.log.Error("初始化超级管理员账户失败", zap.Error(err))
		return err
	}
	m.log.Info(fmt.Sprintf("初始化超级管理员[%s]账户成功，账号：%s, 密码：%s,请及时修改", mUser.Username, mUser.Email, pwd))
	return nil
}
